package ranab.server;

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException; 
import java.net.InetAddress;
import java.util.Vector;
import java.util.Iterator;
import java.util.StringTokenizer;

import ranab.io.IoUtils;
import ranab.util.RegularExpr;

/**
 * This class provides IP restriction functionality.
 * 
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */
public 
class IpRestrictor extends Vector {
    
    private final static String LINE_SEP = System.getProperty("line.separator", "\n");
        
    private File mIpFile;
    private boolean mbAllowIp;
    
    /**
     * Read the IP restriction config file.
     *
     * @param file IP restrictor file object
     */
    public IpRestrictor(File file, boolean allow) {
        mIpFile = file;
        mbAllowIp = allow;
        readFile();
    }
    
    /**
     * Allow Ip
     */
    public boolean isAllowIp() {
        return mbAllowIp;
    }
    
    /**
     * Read the list from the file.
     */
    public synchronized void readFile() {
        clear();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(mIpFile));
            String line = null;
            while((line = br.readLine()) != null) {
                line = line.trim();
                if(!line.equals("")) {
                    add(line);
                }
            }
        }
        catch(IOException ex) {
            ex.printStackTrace();
        }
        finally {
          IoUtils.close(br);
        }
    }
    
    /**
     * Get IP resrictor file object.
     */
    public File getFile() {
        return mIpFile;
    }
     
    /**
     * Save this IP restriction list.
     */
    public synchronized void writeFile() throws IOException {
        FileWriter fw = null;
        try {
            fw = new FileWriter(mIpFile);
            for(Iterator ipIt = iterator(); ipIt.hasNext(); ) {
                fw.write(ipIt.next().toString());
                fw.write(LINE_SEP);
            }
        }
        finally {
            IoUtils.close(fw);
        }
    }
    
    
    /**
     * Check IP permission. Compare it with all the entries in the list.
     */
    public boolean hasPermission(InetAddress addr) {
       boolean bMatch = false; 
       for(Iterator ipIt = iterator(); ipIt.hasNext(); ) {
           RegularExpr regExp = new RegularExpr(ipIt.next().toString());
           bMatch = regExp.isMatch(addr.getHostAddress());
           if(bMatch) {
               break;
           }
       } 
       
       if (mbAllowIp) {
           return bMatch;
       }
       else {
           return !bMatch;
       }
    }

}    